<template>
  <a-modal v-model:visible="modalvisible" title="修改用户密码" centered @ok="onSubmit" @cancel="onshutdown" ok-text="修改密码" cancel-text="取消" :ok-button-props="{
      disabled:
        sub.password != '' && sub.newpass != '' && sub.setpass != ''
          ? false
          : true,
    }" :maskClosable="false">
    <a-form :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-form-item label="旧密码">
        <a-input-password v-model:value="sub.password" placeholder="旧密码" />
      </a-form-item>
      <a-form-item label="新密码">
        <a-input-password v-model:value="sub.newpass" placeholder="新密码" />
      </a-form-item>
      <a-form-item label="确认新密码">
        <a-input-password v-model:value="sub.setpass" placeholder="确认新密码" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang='ts'>
import { reactive, SetupContext, toRefs, watch } from "vue";
import { $message } from "@/components/AntDesign/message";
import { updata } from "@/api/userApi/index";
import { AxiosResponse } from "axios";
import router from "@/router";
interface Data {
  sub: {
    password: string;
    newpass: string;
    setpass: string;
  };
}

export default {
  name: "修改密码",
  props: {
    name: String,
    modalvisible: {
      type: Boolean,
      default: false,
    },
  },
  setup(props: any, ctx: SetupContext) {
    const data: Data = reactive({
      sub: {
        password: "",
        newpass: "",
        setpass: "",
      },
    });

    /* 修改 */
    async function onSubmit() {
      const { password, newpass, setpass } = data.sub;
      if (newpass != setpass) {
        $message("error", "两次密码不相同");
        return;
      }
      if (password === setpass) {
        $message("error", "不能修改相同密码");
        return;
      }
      try {
        const uppass: AxiosResponse = await updata({
          name: props.name,
          password,
          setpass,
        });
        ctx.emit("onshutdown", false);
        $message("success", uppass.data.message);
        localStorage.removeItem("token");
        localStorage.removeItem("userdata");
        router.push({ path: "/login" });
      } catch (error) {
        $message("error", error.data.message);
      }
    }

    function onshutdown() {
      ctx.emit("onshutdown", false);
    }

    return {
      ...toRefs(data),
      labelCol: { span: 7 },
      wrapperCol: { span: 14 },
      onSubmit,
      onshutdown,
    };
  },
};
</script>
